package com.ec50n9.server.module.common

/**
 * 状态码：代码 [code] 和提示 [message]
 */
interface StatusCode {
    val code: Int
    val message: String
}

/**
 * 基础状态码
 */
enum class BaseCode(override val code: Int, override val message: String) : StatusCode {
    SUCCESS(1000, "请求成功"),
    FAILED(1001, "请求失败"),
    VALIDATE_ERROR(1002, "参数校验失败"),
    RESPONSE_PACK_ERROR(1003, "response返回包装失败")
}

/**
 * 业务状态码
 */
enum class AppCode(override val code: Int, override val message: String) : StatusCode {
    APP_ERROR(2000, "业务异常"),
    OBJECT_ALREADY_EXISTS(2003, "对象已存在"),
    OBJECT_NOT_FOUND(2004, "找不到对象"),
    DATA_INTEGRITY_VIOLATION(2005, "对象与其他对象存在关联关系"),
    OBJECT_NOT_SUPPORTED(2006, "不支持的对象"),
    OUT_OF_RANGE(2007, "数值超出范围")
}

/**
 * 登录状态码
 */
enum class AuthCode(override val code: Int, override val message: String) : StatusCode {
    NOT_LOGIN(3001, "未登录"),
    NOT_PERMISSION(3002, "权限不足"),
    AUTH_FAIL(3003, "用户名或密码错误")
}

/**
 * 返回结果封装
 */
data class AjaxResult<T>(
    var success: Boolean,
    var code: Int,
    var message: String?,
    var data: T?
) {

    constructor(statusCode: StatusCode, success: Boolean = true, data: T? = null) : this(
        success,
        statusCode.code,
        statusCode.message,
        data
    )

    companion object {
        fun <T> success(statusCode: StatusCode, data: T) = AjaxResult(statusCode, true, data)
        fun <T> success(data: T) = success(BaseCode.SUCCESS, data)

        fun fail(statusCode: StatusCode) = AjaxResult(statusCode, false, null)

        fun fail(statusCode: StatusCode, message: String?): AjaxResult<Nothing> {
            val ajaxResult = fail(statusCode)
            ajaxResult.message = message
            return ajaxResult
        }

        fun fail(message: String) = fail(BaseCode.FAILED, message)
    }
}